//
//  ConNewMapVc.m
//  Shengzhuli
//
//  Created by FXGuo on 2018/1/31.
//  Copyright © 2018年 kamangkeji. All rights reserved.
//

#import "ConNewMapVc.h"
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import <BaiduMapAPI_Utils/BMKUtilsComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import "MyAnimatedAnnotationView.h"
#import "MBProgressHUD+MJ.h"
#import "BMKPointCustomAnnotation.h"
#import "NewMapModel.h"
#import "BMKCustomPaoPaoView.h"
#import "NaviView.h"
#import "ConeBaseViewController.h"
#import "NewHomeNetwork.h"

#define NaviH 84
@interface ConNewMapVc ()<BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate>

@property (nonatomic,weak) BMKMapView *mapView;
@property (nonatomic,strong) BMKLocationService *locService;
@property (nonatomic,strong) BMKGeoCodeSearch *geocodesearch;
@property (nonatomic,strong) BMKUserLocation *userLocation;

@property (nonatomic,strong) NSMutableArray *annotations;
@property (nonatomic,strong) NaviView *navi;

@property (nonatomic,strong) NSMutableArray *bases;//基地列表
@property (nonatomic,strong) NewMapModel *selectModel;//选中的
@end

@implementation ConNewMapVc

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"基地与会所";
    [self setUpMapView];
    [self getBaseList];
}

- (void)setUpMapView
{
    BMKMapView *map = [[BMKMapView alloc]initWithFrame:CGRectMake(0, 0, ScreenW, ScreenH-SafeAreaTopHeight)];
    map.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
    map.showsUserLocation = YES;//显示定位图层
    map.zoomLevel = 14;
    [self.view addSubview:map];
    self.mapView = map;
    
    self.locService = [[BMKLocationService alloc]init];
    [self.locService startUserLocationService];
    self.geocodesearch = [[BMKGeoCodeSearch alloc]init];
    
    NSArray *imgs = @[@"jidi",@"驿站"];
    NSArray *titles = @[@"  代表基地  ",@"  代表驿站  "];
    
    for (NSInteger i=0; i<2; i++) {
        UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(10, 30+41*i, 30, 41)];
        img.image = GetImage(imgs[i]);
        [self.view addSubview:img];
        
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(img.frame)+10, img.y+10, 80, 20)];
        lab.text = titles[i];
        lab.backgroundColor = RGBColorA(234, 111, 90, 0.6);
        lab.textColor = [UIColor whiteColor];
        lab.font = Font(15);
        lab.layer.cornerRadius = 3;
        lab.clipsToBounds = YES;
        [self.view addSubview:lab];
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.mapView.delegate = self;
    self.locService.delegate = self;
    self.geocodesearch.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.mapView.delegate = nil;
    self.locService.delegate = nil;
    self.geocodesearch.delegate = nil;
}

#pragma mark -------------------添加标注------------------------
// 添加动画Annotation
- (void)addAnimatedAnnotation
{
    [self.mapView removeOverlays:self.mapView.overlays];
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    for (NewMapModel *model in self.bases) {
        BMKPointCustomAnnotation *animated= [[BMKPointCustomAnnotation alloc]init];
        animated.customeModel = model;
        [self.annotations addObject:animated];
    }
    [self.mapView addAnnotations:self.annotations];
}
// 根据anntation生成对应的View
- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    //动画annotation
    if ([annotation isKindOfClass:[BMKPointCustomAnnotation class]]) {
        BMKPointCustomAnnotation *an = (BMKPointCustomAnnotation *)annotation;
        NSString *AnnotationViewID = @"AnimatedAnnotation";
        MyAnimatedAnnotationView *annotationView = (MyAnimatedAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        if (annotationView == nil) {
            annotationView = [[MyAnimatedAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
        }
        annotationView.model = an.customeModel;
        if (an.customeModel.clubType == 2) {
            annotationView.imgStr = @"jidi";
        }else if (an.customeModel.clubType == 3) {
            annotationView.imgStr = @"驿站";
        }else {
            annotationView.imgStr = @"jidi";
        }
        UIView *cView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
        UILabel *lab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
        lab.text = annotation.title;
        lab.font = Font(15);
        lab.textColor = [UIColor whiteColor];
        lab.layer.cornerRadius = 5.0;
        lab.clipsToBounds = YES;
        lab.textAlignment = NSTextAlignmentCenter;
        lab.backgroundColor = RGBA(0, 0, 0, 0.8);
        [cView addSubview:lab];
        lab.width = [annotation.title sizeWithAttributes:@{NSFontAttributeName:Font(15)}].width+20;
        cView.width = lab.width;
        BMKCustomPaoPaoView *paopao = [[BMKCustomPaoPaoView alloc]initWithCustomView:cView];
        paopao.frame = CGRectMake(0, 0, lab.width, 30);
        paopao.model = an.customeModel;
        annotationView.paopaoView = paopao;
        paopao.userInteractionEnabled = YES;
        return annotationView;
    }
    return nil;
}
- (void)mapView:(BMKMapView *)mapView didSelectAnnotationView:(BMKAnnotationView *)view
{
    if ([view isKindOfClass:[MyAnimatedAnnotationView class]]) {
        MyAnimatedAnnotationView *anView = (MyAnimatedAnnotationView *)view;
        self.navi.model = anView.model;
        self.selectModel = anView.model;
        [self.view addSubview:self.navi];
        [UIView animateWithDuration:0.3 animations:^{
            self.navi.y = ScreenH-SafeAreaTopHeight-NaviH;
        }];
        NSLog(@"paopaoclick---%@",anView.model.clubName);
    }
}
// 当点击annotation view弹出的泡泡时，调用此接口
- (void)mapView:(BMKMapView *)mapView annotationViewForBubble:(BMKAnnotationView *)view;
{
    [self.mapView deselectAnnotation:view.annotation animated:YES];
    MyAnimatedAnnotationView *anView = (MyAnimatedAnnotationView *)view;
    ConeBaseViewController *vc = [[ConeBaseViewController alloc]init];
    vc.mapModel = anView.model;
    [self.navigationController pushViewController:vc animated:YES];
}
//百度地图单击
- (void)mapView:(BMKMapView *)mapView onClickedMapBlank:(CLLocationCoordinate2D)coordinate
{
    [UIView animateWithDuration:0.3 animations:^{
        self.navi.y = ScreenH-SafeAreaTopHeight;
    }];
}
#pragma mark -------------------定位相关 用户位置更新后，会调用此函数------------------------
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    self.userLocation = userLocation;
    if (self.bases.count > 0) {
        [self calculateDistance];
    }
    [self reverseGeocodeWithPt:userLocation.location.coordinate];
    [self.locService stopUserLocationService];
}
//定位失败后需要提示
- (void)didFailToLocateUserWithError:(NSError *)error
{
    [MBProgressHUD showError:@"定位失败" toView:self.view];
}
#pragma mark ---------------地理编码-------------
-(void)reverseGeocodeWithPt:(CLLocationCoordinate2D)pt
{
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
    BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag) {
        NSLog(@"反geo检索发送成功");
    }else {
        NSLog(@"反geo检索发送失败");
    }
}
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    self.userLocation.title = [NSString stringWithFormat:@"我在%@附近",result.addressDetail.streetName];
    [self.mapView updateLocationData:self.userLocation];
    [self.mapView setCenterCoordinate:self.userLocation.location.coordinate animated:YES];
    //自定义定位点的大头针跟
//    self.mapView selectAnnotation: animated:
}
//导航操作
- (void)showAlertAction
{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"导航" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"百度地图" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self openNativeNavi];
    }];
    [alertVC addAction:actionOne];
    UIAlertAction *actionTwo = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVC addAction:actionTwo];
    [self presentViewController:alertVC animated:YES completion:nil];
}
//打开客户端导航
- (void)openNativeNavi {
    BMKOpenDrivingRouteOption *opt = [[BMKOpenDrivingRouteOption alloc] init];
    BMKPlanNode* start = [[BMKPlanNode alloc]init];
    start.pt = self.userLocation.location.coordinate;
//    start.name = self.userLocation.address;
    opt.startPoint = start;
    
    BMKPlanNode* end = [[BMKPlanNode alloc]init];
    end.pt = CLLocationCoordinate2DMake(self.selectModel.latitude, self.selectModel.longitude);
    end.name = self.selectModel.clubName;
    opt.endPoint = end;
    
    //指定返回自定义scheme
    opt.appScheme = @"funearth://playEarth.dingguagua.com";
    //调启百度地图客户端导航
    BMKOpenErrorCode code = [BMKOpenRoute openBaiduMapDrivingRoute:opt];
    NSLog(@"%d", code);
}

#pragma mark --------------获取基地列表----------------
- (void)getBaseList
{
    [self showWaiter];
    NSMutableDictionary *parames = [NSMutableDictionary dictionary];
    if (self.type) {
        parames[@"type"] = @(self.type);
    }
    [NewHomeNetwork getBaseListWithParame:parames response:^(BOOL success, NSString *msg, NSArray *lists) {
        [self hideWaiter];
        if (success) {
            [self.bases addObjectsFromArray:lists];
            if (self.userLocation) {
                [self calculateDistance];
            }
            [self addAnimatedAnnotation];
        }else {
            [MBProgressHUD showError:msg];
        }
    }];
}

- (void)calculateDistance
{
    for (NewMapModel *model in self.bases) {
        CLLocationDistance distance = BMKMetersBetweenMapPoints(BMKMapPointForCoordinate(self.userLocation.location.coordinate),BMKMapPointForCoordinate(CLLocationCoordinate2DMake(model.latitude,model.longitude)));
        model.distance = [NSString stringWithFormat:@"%.1f公里",distance/1000];
    }
}

- (NSMutableArray *)annotations
{
    if (!_annotations) {
        _annotations = [NSMutableArray array];
    }
    return _annotations;
}
- (NaviView *)navi
{
    if (!_navi) {
        _navi = [NaviView naViView];
        _navi.frame = CGRectMake(0, ScreenH-SafeAreaTopHeight, ScreenW, 84);
        __WEAK
        _navi.naviBlock = ^(){
            [weakSelf showAlertAction];
        };
    }
    return _navi;
}
- (NSMutableArray *)bases
{
    if (!_bases) {
        _bases = [NSMutableArray array];
    }
    return _bases;
}

@end
